
from google.appengine.api import images
from google.appengine.api.urlfetch import fetch
from google.appengine.ext import db, webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from models import Dish
from operator import itemgetter, attrgetter
import base64
import simplejson as json
import urllib2


            
#This class is responsible for returning a list of the user's favorite dishes to android
class UserFavDishes(webapp.RequestHandler):
    
    def get(self):
        self.response.out.write("In GET\n");
      
    def post(self):
        userId = self.request.get("userId")
        self.getFavDishesList(userId)
        
    #Returns a list from a given  list of ingredients in string form separted by commas
    @staticmethod 
    def getIngredients(ingredientString):
        
        ingredientNames = ingredientString.split(',')
        result = []
        for ingName in ingredientNames:
            query = db.GqlQuery("SELECT __key__ FROM Ingredient WHERE name = :1 LIMIT 1", ingName)
            if query.count(1) != 0:
                result.append(query[0])
        return result    
    #This method takes a user id and dish key, returns true if the the dish has an ingredient the user hates and the user has the neverShow att set to true  
    @staticmethod
    def doesHate(userId, dishKey, userHateIngsNames, userNeverShow):
        userQuery = db.GqlQuery("SELECT * FROM User WHERE android_id = :1 LIMIT 1", userId);
        dishQuery = db.GqlQuery("SELECT * FROM Dish WHERE __key__ = :1 LIMIT 1", dishKey);
        userHateList = UserFavDishes.getIngredients(userHateIngsNames);
        user = None
        dish = None
        if userQuery.count(1) != 0 :
            user = userQuery.get()
            if dishQuery.count(1) != 0 :
                dish = dishQuery.get()
                if userNeverShow == False:
                    return False;    
                for ingredient in dish.ingredients:
                    if ingredient in userHateList:
                        return True;
            else:
                return False
        else:
            return False;
    #Given the android_id this method sends a list of the user's favorite dishes to android
    def getFavDishesList(self, userId):
        userQuery = db.GqlQuery("SELECT * FROM User WHERE android_id = :1 LIMIT 1", userId);
        
        favDishResult = []
        if userQuery.count(1) == 0 :
            self.response.out.write("No users were found")
        else:
            user = userQuery.get();
            favDishesKeys = user.favDishes;
            for dishKey in favDishesKeys:
                dishQuery = db.GqlQuery("SELECT * FROM Dish WHERE __key__ = :1 LIMIT 1", dishKey);
                if dishQuery.count(1) != 0 :
                    dish = dishQuery.get()
                    if dish.img:
                        favDishResult.append(dict(name=str(dish.name), img=base64.b64encode(dish.img), key=str(dish.key())))
                    else:
                        favDishResult.append(dict(name=str(dish.name), key=str(dish.key())))
            self.response.headers['Content-Type'] = 'text/plain'
            self.response.out.write(json.dumps(favDishResult))
            return True
#This class is responsible for adding a dish from android to the user's list of favorite dishes
class addUserFavDishes(webapp.RequestHandler):
    def get(self):
        self.response.out.write("In GET\n");
      
    def post(self):
        userId = self.request.get("userId")
        dishKey = self.request.get("key")
        self.addFavDish(userId, dishKey)
        
    #provided with the android_id and a dish key, this method adds the dish key to the user's list of favorite dishes
    def addFavDish(self, userId, dishKey):
        userQuery = db.GqlQuery("SELECT * FROM User WHERE android_id = :1 LIMIT 1", userId);
        if userQuery.count(1) == 0 :
            self.response.out.write("No users were found")
        else:
            user = userQuery.get()
            if db.Key(dishKey) not in user.favDishes:
                user.favDishes.append(db.Key(dishKey))
                user.put()
            self.response.out.write("Dish added successfully")

application = webapp.WSGIApplication([('/user_info/get_fav_dishes', UserFavDishes), ('/user_info/add_fav_dishes', addUserFavDishes)], debug=True)
  
def main():
    run_wsgi_app(application)
    
if __name__ == "__main__":
    main()
